const jwt = require('jsonwebtoken');
const fs = require('fs')
const privateKey = fs.readFileSync('private.key').toString()
module.exports = {
    'login': (ctx) => {
        const { username, password } = ctx.request.body
        /** 管理员 */
        if (username === 'admin' && password === '888888') {
            const token = jwt.sign({ name: 'JACK', avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80', role: 'ADMIN' }, privateKey)
            ctx.body = { code: 20000, data: { token } }
        }
        /** 用户 */
        else if (username === 'user' && password === '888888') {
            const token = jwt.sign({ name: 'JACK', avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80', role: 'USER' }, privateKey)
            ctx.body = { code: 20000, data: { token } }
        }
        /** 账号密码错误 */
        else {
            ctx.body = { code: 40001, data: { msg: '账号/密码错误...' } }
        }
    },
    'info': (ctx) => {
        const { token } = ctx.request.body
        try {
            const decoded = jwt.verify(token, privateKey)
            ctx.body = { code: 20000, data: decoded }
        } catch (err) {
            ctx.status = 401
            ctx.body = { code: 40001, data: { msg: '验证失败...请重新登陆' } }
        }
    }
}